package com.dev.weixin.tools.utils.policy;

import java.nio.charset.UnsupportedCharsetException;
import java.util.Map;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author 飘渺青衣
 * @see
 */
public class JsonRequestPolicy<T> extends GetRequestPolicy<T> {
	
	private Object jsonObject;
	
	public JsonRequestPolicy(
			String url, String encoding, 
			Map<String, String> getParameters, Object jsonObject, Class<T> resultClass) {
		super(url, encoding, getParameters, resultClass);
		this.jsonObject = jsonObject;
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.tools.utils.policy.RequestPolicy#request(org.apache.http.client.methods.HttpPost, com.fasterxml.jackson.databind.ObjectMapper)
	 */
	@Override
	public void request(HttpPost post, ObjectMapper mapper) {
		StringEntity s_entity = null;
    	if(this.jsonObject != null) {
    		ContentType contentType = ContentType.create("text/plain", this.getEncoding());
    		if(jsonObject instanceof String) {
    			LOG.info(jsonObject);
    			s_entity = new StringEntity((String) jsonObject, contentType);
    		} else {
    			try {
    				String json = mapper.writeValueAsString(jsonObject);
    				LOG.info(json);
					s_entity = new StringEntity(json, contentType);
				} catch (UnsupportedCharsetException | JsonProcessingException e) {
					e.printStackTrace();
				} 
    		}
    		post.setEntity(s_entity);
    	}
	}

}
